library(tidyverse)
## ── Attaching packages ────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.2     ✓ purrr   0.3.4
## ✓ tibble  3.0.3     ✓ dplyr   1.0.2
## ✓ tidyr   1.1.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ───────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
download.file(url = "https://ndownloader.figshare.com/files/2292169",
              destfile = "data/surveys_complete.csv")
surveys_complete <- read_csv("data/surveys_complete.csv")
## Parsed with column specification:
## cols(
##   record_id = col_double(),
##   month = col_double(),
##   day = col_double(),
##   year = col_double(),
##   plot_id = col_double(),
##   species_id = col_character(),
##   sex = col_character(),
##   hindfoot_length = col_double(),
##   weight = col_double(),
##   genus = col_character(),
##   species = col_character(),
##   taxa = col_character(),
##   plot_type = col_character()
## )

#Plotting with ggplot2

#To build a ggplot, we will use the following basic template:

ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length)) +
  geom_point()
## Warning: Removed 4048 rows containing missing values (geom_point).

Challenge (Optional)

install.packages("hexbin")
## Installing package into '/home/rstudio-user/R/x86_64-pc-linux-gnu-library/4.0'
## (as 'lib' is unspecified)
library("hexbin")
#Assign plot to a variable
surveys_plot <- ggplot(data = surveys_complete, 
                       mapping = aes(x = weight, y = hindfoot_length))
#Draw Plot
surveys_plot + 
  geom_point()
## Warning: Removed 4048 rows containing missing values (geom_point).

surveys_plot + 
  geom_hex()
## Warning: Removed 4048 rows containing non-finite values (stat_binhex).

#Building your plots iteratively

#Define the Dataset
ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length)) +
    geom_point()
## Warning: Removed 4048 rows containing missing values (geom_point).

#Modify the Dataset
ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length)) +
    geom_point(alpha = 0.1)
## Warning: Removed 4048 rows containing missing values (geom_point).

#Adding Colors

ggplot(data = surveys_complete, mapping = aes(x = weight, y = hindfoot_length)) +
    geom_point(alpha = 0.1, color = "blue")
## Warning: Removed 4048 rows containing missing values (geom_point).

#Adding color to each species with species_id:

ggplot(data = surveys_complete, mapping = aes(x = weight, y = hindfoot_length)) +
    geom_point(alpha = 0.1, aes(color = species_id))
## Warning: Removed 4048 rows containing missing values (geom_point).

#Challenge 1

#Use what you just learned to create a scatter plot of weight over species_id with the plot types showing in different colors. Is this a good way to show this type of data?

ggplot(data = surveys_complete, 
       mapping = aes(x = species_id, y = weight)) +
   geom_point(aes(color = plot_type))
## Warning: Removed 2503 rows containing missing values (geom_point).

#Boxplot

#We can use boxplots to visualize the distribution of weight within each species:

ggplot(data = surveys_complete, mapping = aes(x = species_id, y = weight)) +
    geom_boxplot()
## Warning: Removed 2503 rows containing non-finite values (stat_boxplot).

# By adding points to the boxplot, we can have a better idea of the number of measurements and of their distribution:

ggplot(data = surveys_complete, mapping = aes(x = species_id, y = weight)) +
    geom_boxplot(alpha = 0) +
    geom_jitter(alpha = 0.3, color = "tomato")
## Warning: Removed 2503 rows containing non-finite values (stat_boxplot).
## Warning: Removed 2503 rows containing missing values (geom_point).

Challenge 2

# Replace the box plot with a violin plot
ggplot(data = surveys_complete, mapping = aes(x = species_id, y = weight)) +
    geom_violin() 
## Warning: Removed 2503 rows containing non-finite values (stat_ydensity).

# Incrementally adding commands: scale_y_log10
ggplot(data = surveys_complete, mapping = aes(x = species_id, y = weight)) +
    geom_violin() +
  scale_y_log10()
## Warning: Removed 2503 rows containing non-finite values (stat_ydensity).

#So far, we’ve looked at the distribution of weight within species. Try making a new plot to explore the distribution of another variable within each species.

ggplot(data = surveys_complete, mapping = aes(x = species_id, y = hindfoot_length)) +
    geom_boxplot() +
    geom_jitter(aes(color = "plot_id"))
## Warning: Removed 3348 rows containing non-finite values (stat_boxplot).
## Warning: Removed 3348 rows containing missing values (geom_point).

Lab 5 Challenges: Plotting Time Series Date

#Let’s calculate number of counts per year for each genus. First we need to group the data and count records within each group:

yearly_counts <- surveys_complete %>%
  count(year, genus)
#Timelapse data can be visualized as a line plot with years on the x-axis and counts on the y-axis:
ggplot(data = yearly_counts, aes(x = year, y = n, group = genus)) +
     geom_line()

# The data is plotted all together and needs to be modified
#Modifying the aesthetic function to include: group = genus
ggplot(data = yearly_counts, aes(x = year, y = n, group = genus)) +
     geom_line()

#We will be able to distinguish species in the plot if we add colors (using color also automatically groups the data):

ggplot(data = yearly_counts, aes(x = year, y = n, color = genus)) +
    geom_line()

#Integrating the pipe operator with ggplot2

#In the previous lesson, we saw how to use the pipe operator %>% to use different functions in a sequence and create a coherent workflow. We can also use the pipe operator to pass the data argument to the ggplot() function. 

yearly_counts %>% 
    ggplot(mapping = aes(x = year, y = n, color = genus)) +
    geom_line()

# The pipe operator can also be used to link data manipulation with consequent data visualization.

yearly_counts_graph <- surveys_complete %>%
    count(year, genus) %>% 
    ggplot(mapping = aes(x = year, y = n, color = genus)) +
    geom_line()

yearly_counts_graph

#Faceting

#ggplot has a special technique called faceting that allows the user to split one plot into multiple plots based on a factor included in the dataset. We will use it to make a time series plot for each species:

ggplot(data = yearly_counts, aes(x = year, y = n)) +
  geom_line() +
  facet_wrap(facets = vars(genus))
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

# Now we would like to split the line in each plot by the sex of each individual measured. To do that we need to make counts in the data frame grouped by year, genus, and sex:

 yearly_sex_counts <- surveys_complete %>%
                      count(year, genus, sex)
# We can now make the faceted plot by splitting further by sex using color (within a single plot):

ggplot(data = yearly_sex_counts, mapping = aes(x = year, y = n, color = sex)) +
  geom_line() +
  facet_wrap(facets =  vars(genus))
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

#You can also organise the panels only by rows (or only by columns):

# One column, facet by rows
ggplot(data = yearly_sex_counts, 
       mapping = aes(x = year, y = n, color = sex)) +
  geom_line() +
  facet_grid(rows = vars(genus))
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

# One row, facet by column
ggplot(data = yearly_sex_counts, 
       mapping = aes(x = year, y = n, color = sex)) +
  geom_line() +
  facet_grid(cols = vars(genus))
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

ggplot2 themes

# There are pre-loaded themes available that change the overall appearance of the graph without much effort.For example, we can change our previous graph to have a simpler white background using the theme_bw() function, and a darker background using the theme_dark function:

ggplot(data = yearly_sex_counts, 
        mapping = aes(x = year, y = n, color = sex)) +
     geom_line() +
     facet_wrap(vars(genus)) +
     theme_bw()
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

ggplot(data = yearly_sex_counts, 
        mapping = aes(x = year, y = n, color = sex)) +
     geom_line() +
     facet_wrap(vars(genus)) +
     theme_dark()
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

# There are other functions that can change the background as a starting point to create a new hand-crafted theme: theme_minimal() and theme_light() are popular, and theme_void()

Challenge 1

# Use what you just learned to create a plot that depicts how the average weight of each species changes through the years.

yearly_weight <- surveys_complete %>%
                group_by(year, species_id) %>%
                 summarize(avg_weight = mean(weight))
## `summarise()` regrouping output by 'year' (override with `.groups` argument)
ggplot(data = yearly_weight, mapping = aes(x=year, y=avg_weight)) +
   geom_line() +
   facet_wrap(vars(species_id)) +
   theme_void()
## Warning: Removed 89 row(s) containing missing values (geom_path).
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

Customization

#Now, let’s change names of axes to something more informative than ‘year’ and ‘n’ and add a title to the figure:

ggplot(data = yearly_sex_counts, aes(x = year, y = n, color = sex)) +
    geom_line() +
    facet_wrap(vars(genus)) +
    labs(title = "Observed genera through time",
         x = "Year of observation",
         y = "Number of individuals") +
    theme_dark()
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

# The axes have more informative names, but their readability can be improved by increasing the font size. This can be done with the generic theme() function:

ggplot(data = yearly_sex_counts, mapping = aes(x = year, y = n, color = sex)) +
    geom_line() +
    facet_wrap(vars(genus)) +
    labs(title = "Observed genera through time",
        x = "Year of observation",
        y = "Number of individuals") +
    theme_dark() +
    theme(text=element_text(size = 16))
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

#Let’s change the orientation of the labels and adjust them vertically and horizontally so they don’t overlap. You can use a 90 degree angle, or experiment to find the appropriate angle for diagonally oriented labels. We can also modify the facet label text (strip.text) to italicize the genus names:

ggplot(data = yearly_sex_counts, mapping = aes(x = year, y = n, color = sex)) +
    geom_line() +
    facet_wrap(vars(genus)) +
    labs(title = "Observed genera through time",
        x = "Year of observation",
        y = "Number of individuals") +
    theme_dark() +
    theme(axis.text.x = element_text(colour = "grey20", size = 12, angle = 90, hjust = 0.5, vjust = 0.5),
                        axis.text.y = element_text(colour = "grey20", size = 12),
                        strip.text = element_text(face = "italic"),
                        text = element_text(size = 16))
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

#If you like the changes you created better than the default theme, you can save them as an object to be able to easily apply them to other plots you may create:

grey_theme <- theme(axis.text.x = element_text(colour="grey20", size = 12, 
                                               angle = 90, hjust = 0.5, 
                                               vjust = 0.5),
                    axis.text.y = element_text(colour = "grey20", size = 12),
                    text=element_text(size = 16))

ggplot(surveys_complete, aes(x = species_id, y = hindfoot_length)) +
    geom_boxplot() +
    grey_theme
## Warning: Removed 3348 rows containing non-finite values (stat_boxplot).

Challenge 2

# With all of this information in hand, please take another five minutes to either improve one of the plots generated in this exercise or create a beautiful graph of your own.

ggplot(data = yearly_sex_counts, mapping = aes(x = year, y = n, color = sex)) +
    geom_line() +
    facet_wrap(vars(genus)) +
    labs(title = "Observed genera through time",
        x = "Year of observation",
        y = "Number of individuals") +
    theme_dark() +
    theme(axis.text.x = element_text(colour = "grey20", size = 12, angle = 90, hjust = 0.5, vjust = 0.5),
                        axis.text.y = element_text(colour = "grey20", size = 7),
                        strip.text = element_text(face = "italic"),
                        text = element_text(size = 11))
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?
## geom_path: Each group consists of only one observation. Do you need to adjust
## the group aesthetic?

Application written in R (R Core Team 2015) using the Shiny framework (Chang et al. 2015).

References

Chang, W., J. Cheng, JJ. Allaire, Y. Xie, and J. McPherson. 2015. “Shiny: Web Application Framework for R. R Package Version 0.12.1.” Computer Program. http://CRAN.R-project.org/package=shiny.

R Core Team. 2015. “R: A Language and Environment for Statistical Computing.” Journal Article. http://www.R-project.org.